package com.programmingteam.wallpaperslideshow;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;

public class PreferencesActivity extends PreferenceActivity {
	private static final String TAG = "WallpaperSlideshow";

	// Preferences converter (String to Int)
	private SharedPreferences.OnSharedPreferenceChangeListener prefListener =
			new SharedPreferences.OnSharedPreferenceChangeListener() {
				@Override
				public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
					Editor editor;
					String value;
					int intValue;
					Log.d(TAG, "<PREFERENCES_CONVERTER>New STRING (key=" + key + ")");

					if (key.equals("string_timerinterval")) {
						value = sharedPreferences.getString("string_timerinterval", "-1");
						intValue = Integer.parseInt(value);
						intValue = intValue > 0 ? intValue : 5;
						editor = sharedPreferences.edit();
						editor.putInt(Config.SharedKeys.EVENT_TIMER_INTERVAL, intValue);
						editor.commit();
					}

					if (key.equals("string_distanceaccuracy")) {
						value = sharedPreferences.getString("string_distanceaccuracy", "-1");
						intValue = Integer.parseInt(value);
						editor = sharedPreferences.edit();
						editor.putInt(Config.SharedKeys.EVENT_LOCATION_DISTANCE, intValue);
						editor.commit();
					}

					if (key.equals("string_imagequality")) {
						value = sharedPreferences.getString("string_imagequality", "-1");
						intValue = Integer.parseInt(value);
						editor = sharedPreferences.edit();
						editor.putInt(Config.SharedKeys.IMAGEQUALITY, intValue);
						editor.commit();
					}
				}
			};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "Preferences: onResume()");
		PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
				.registerOnSharedPreferenceChangeListener(prefListener);
	}

	@Override
	protected void onPause() {
		Log.d(TAG, "Preferences: onPause()");
		PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
				.unregisterOnSharedPreferenceChangeListener(prefListener);
		super.onPause();
	}

}
